package org.karelun.gef.commands;

import org.karelun.gef.model.AbstractConnectionModel;
import org.karelun.gef.model.AttributeModel;
import org.karelun.gef.model.MethodModel;
import org.karelun.gef.model.Node;

public class ReconnectConnectionCommand extends AbstractCommand{
	private AbstractConnectionModel connection;
	private Node newSource=null;
	private Node newTarget=null;
	private Node oldSource=null;
	private Node oldTarget=null;
	
	public void execute() {
		if(newSource !=null){
			if(newSource instanceof AttributeModel || newSource instanceof MethodModel){
				oldSource = connection.getSource();
				reconnectSource(oldSource);
			}else{
				oldSource = connection.getSource();
				reconnectSource(newSource);
			}			
		}
		else if (newTarget != null ) {
			 if(newTarget instanceof AttributeModel ||newTarget instanceof MethodModel){
					oldTarget = connection.getTarget();
					reconnectTarget(oldTarget);
			 }else{
				 oldTarget = connection.getTarget();
				 reconnectTarget(newTarget);
			 }			
		}
	}

	private void reconnectSource(Node source) {
		connection.detachSource();
		connection.setSource(source);
		connection.attachSource();
	}

	private void reconnectTarget(Node target) {
		connection.detachTarget();
		connection.setTarget(target);
		connection.attachTarget();
	}

	public void setConnectionModel(Object model) {
		connection = (AbstractConnectionModel) model;
	}

	public void setNewSource(Object model) {
		newSource = (Node) model;
	}

	public void setNewTarget(Object model) {
		newTarget = (Node) model;
	}

	public void undo() {	
		if (oldSource != null)
			reconnectSource(oldSource);
		if (oldTarget != null)
			reconnectTarget(oldTarget);
		oldSource = null;
		oldTarget = null;
	}

	@Override
	public void redo() {
		execute();
	}
}
